import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { FetchService } from '../../../core/net/fetch.service';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
export interface Data {
    id: number;
    name: string;
    year: string;
    manager: string;
    telephone: string;
    type: string;
    districtId: number;
    address: string;
}
@Component({
    selector: 'app-pm-project-files',
    templateUrl: './pm-project-files.component.html',
    styleUrls: ['./pm-project-files.component.scss']
})
export class PmProjectFilesComponent implements OnInit {
    searchForm: FormGroup;
    yearOptions = [];
    isAllDisplayDataChecked = false;
    isIndeterminate = false;
    listOfDisplayData: Data[] = [];
    listOfAllData: Data[] = [];
    mapOfCheckedId: { [key: string]: boolean } = {};
    numberOfChecked = 0;
    delDisable = true;

    form: FormGroup;
    modalTitle: string = '';
    modalShow: boolean = false;
    nzBodyStyle: any = {
        padding: '16px 20px 0'
    };
    allChecked = false;
    indeterminate = false;
    checkId = [];

    projectChartOption = {
        color: ['#3398DB'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            splitLine: {
                show: true
            },
            data: []
        },
        yAxis: {
            type: 'value',
            splitLine: {
                show: true
            },
            splitArea: { show: true }
        },
        series: [
            {
                name: '数量',
                type: 'bar',
                barWidth: '60%',
                data: []
            }
        ]
    };
    projectChartMergeOption;

    pieChartOption = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
            bottom: 0,
            data: ['信息化工程', '涉外工程']
        },
        series: [
            {
                name: '访问来源',
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: [
                    { value: 335, name: '信息化工程' },
                    { value: 310, name: '涉外工程' },
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    pieChartMergeOption;

    constructor(private fb: FormBuilder,
                private fetchService: FetchService,
                private router: Router,
                private message: NzMessageService) {
        const date = new Date();
        const year = date.getFullYear();
        for (let i = year - 10; i <= year; i++) {
            this.yearOptions.unshift(i);
        }
        this.searchForm = this.fb.group({
            name: [],
            year: [],
            type: []
        });
    }

    ngOnInit(): void {
        this.queryInfo();
        this.getChartData();
    }

    queryInfo(): void {
        // const param = {
        //     name: this.searchForm.value.name,
        //     year: this.searchForm.value.year,
        //     type: this.searchForm.value.type
        // };
        this.fetchService.post<any>('archives/wrsProjectInfo/list', this.searchForm.value).subscribe(res => {
            this.listOfAllData = res.list;
        });
    }

    getChartData(): void {
        // {"data":{"typeList":[{"type":"1","num":2}],"yearList":[{"year":"2015","num":1},{"year":"2019","num":1}]}}
        this.fetchService.post<any>('archives/wrsProjectInfo/statistic', {}).subscribe(res => {
            this.projectChartMergeOption = {
                xAxis: {
                    data: res.yearList.map(item => item.year + '年')
                },
                series: [
                    {
                        data: res.yearList.map(item => item.num)
                    }
                ]
            };
        });
    }

    currentPageDataChange($event: Data[]): void {
        this.listOfDisplayData = $event;
        this.refreshStatus();
    }

    refreshStatus(): void {
        console.log(this.mapOfCheckedId);
        console.log(this.listOfDisplayData);
        console.log(Object.keys(this.mapOfCheckedId).length);
        // this.delDisable = Object.keys(this.mapOfCheckedId).length > 0 ? false : true;
        this.isAllDisplayDataChecked = this.listOfDisplayData
            .every(item => this.mapOfCheckedId[item.id]);
        this.isIndeterminate =
            this.listOfDisplayData.some(item => this.mapOfCheckedId[item.id]) &&
            !this.isAllDisplayDataChecked;
        this.numberOfChecked = this.listOfAllData.filter(item => this.mapOfCheckedId[item.id]).length;
        console.log(this.mapOfCheckedId);
    }
    checkAllActive(value: boolean): void {
        console.log(value);
        this.checkId = [];
        this.listOfDisplayData.forEach(item => (this.mapOfCheckedId[item.id] = value));
        this.listOfDisplayData.forEach(item =>
            this.checkId.push(item)
        );
        this.delDisable = (value) ? false : true;
        (value) ? this.checkId = this.checkId : this.checkId = [];

    }

    checkAll(item: any, value: boolean): void {
        if (value) {
            this.checkId.push(item);
        } else {
            this.checkId = this.checkId.filter(items => item.id !== items.id);
        }
        this.delDisable = this.checkId.length > 0 ? false : true;
    }

    openEditModal(item?): void {
        this.router.navigate(['/pm/file-detail'], { queryParams: { id: item.id } });
    }


    onDelete(id) {
        this.fetchService.post('archives/wrsProjectInfo/delete', { ids: [id] }).subscribe(resp => {
            this.message.info('删除成功');
            this.queryInfo();
        });
    }

    onDeleteAll() {
        const ids = [];
        this.checkId.filter((item) => {
            ids.push(item.id);
        });
        this.fetchService.post('archives/wrsProjectInfo/delete', { ids: ids }).subscribe(resp => {
            this.message.info('删除成功');
            this.queryInfo();
        });
    }

    onConfirm() {
        if (!this.form.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        const data = this.form.value;
        if (data.id) {
            this.fetchService.post('archives/wrsProjectInfo/edit', data).subscribe(res => {
                this.modalShow = false;
                this.queryInfo();
            });
        } else {
            this.fetchService.post('archives/wrsProjectInfo/add', data).subscribe(res => {
                this.modalShow = false;
                this.queryInfo();
            });
        }
    }

    onAdd(): void {
        this.router.navigate(['/pm/file-detail'], { queryParams: { id: '' } });
    }

    onCancel() {
        this.modalShow = false;
    }


}
